<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 -->

        <label class="el-form-item-label">所属农场</label>
        <el-select v-model="query.farm_id" filterable placeholder="请选择" style="width: 185px;" class="filter-item">
          <el-option v-for="item in dict.farms" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
        <label class="el-form-item-label">田块编号</label>
        <el-input
          v-model="query.field_code"
          clearable
          placeholder="田块编号"
          style="width: 185px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <label class="el-form-item-label">田块名称</label>
        <el-input
          v-model="query.field_name"
          clearable
          placeholder="田块名称"
          style="width: 185px;"
          class="filter-item"
          @keyup.enter.native="crud.toQuery"
        />
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <crudOperation :permission="permission" />
      <!--表单组件-->
      <el-dialog
        :close-on-click-modal="false"
        :before-close="crud.cancelCU"
        :visible.sync="crud.status.cu > 0"
        :title="crud.status.title"
        width="600px"
      >
        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="120px">
          <el-form-item label="所属农场" prop="farm">
            <el-select v-model="form.farm_id" filterable placeholder="请选择" style="width: 370px;">
              <el-option v-for="item in dict.farms" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="田块编号">
            <el-input v-model="form.field_code" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="田块名称">
            <el-input v-model="form.field_name" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="田块面积">
            <el-input v-model="form.field_area" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="form.remark" style="width: 370px;" />
          </el-form-item>
          <el-form-item label="图片">
            <el-upload
              ref="upload"
              list-type="picture-card"
              class="upload-demo"
              action="#"
              :file-list="fileList"
              :auto-upload="false"
            >
              <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
              <div slot="tip" class="el-upload__tip">只能上传图片文件，且不超过512kb</div>
            </el-upload>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
        </div>
      </el-dialog>
      <!--表格渲染-->
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        size="small"
        style="width: 100%;"
        @selection-change="crud.selectionChangeHandler"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="farm_name" label="所属农场" width="200" />
        <el-table-column prop="field_code" label="田块编号" width="150" />
        <el-table-column prop="field_name" label="田块名称" width="200" />
        <el-table-column prop="field_area" label="田块面积" width="80" />
        <el-table-column prop="remark" label="备注" width="80" />
        <el-table-column
          v-if="checkPer(['admin', 'field:edit', 'field:del'])"
          label="操作"
          width="150px"
          align="center"
        >
          <template slot-scope="scope">
            <udOperation :data="scope.row" :permission="permission" />
            <el-popover
              :ref="scope.row.id"
              v-model="popoverVisible[scope.row.id]"
              v-permission="['admin', 'field:edit']"
              placement="top"
              width="450"
              trigger="manual"
              @show="showPopver(scope.row)"
            >
              <el-row>
                <el-col :span="2"> </el-col>
                <el-col :span="20">
                  <p align="center">请输入GPS坐标</p>
                </el-col>
                <el-col :span="2" align="right">
                  <el-button type="text" size="large" @click="$refs[scope.row.id].doClose()">X</el-button>
                </el-col>
              </el-row>
              <el-form ref="gpsForm" :model="gpsForm">
                <el-form-item
                  v-for="(gps, index) in gpsForm.position"
                  :key="index"
                  :label="'坐标' + (index + 1)"
                  prop="latitude"
                >
                  <el-row>
                    <el-col :span="9">
                      <el-input v-model="gps.longitude" placeholder="经度" type="number"></el-input>
                    </el-col>
                    <el-col :span="9">
                      <el-input v-model="gps.latitude" placeholder="纬度" type="number"></el-input>
                    </el-col>
                    <el-col :span="1">
                      <el-button type="danger" @click.prevent="removePosition(index)">X</el-button>
                    </el-col>
                  </el-row>
                </el-form-item>
                <el-form-item>
                  <el-row>
                    <el-col :span="2">
                      <el-button size="mini" type="text" @click="addPosition()">加行</el-button>
                    </el-col>
                    <el-col class="line" :span="16">&nbsp; </el-col>
                    <el-col :span="2">
                      <el-button size="mini" type="text" @click="$refs[scope.row.id].doClose()">取消</el-button>
                    </el-col>
                    <el-col :span="2">
                      <el-button type="primary" size="mini" @click="savePosition(scope.row)">保存</el-button>
                    </el-col>
                  </el-row>
                </el-form-item>
              </el-form>
              <el-button slot="reference" type="text" size="mini" @click="openPopover(scope.row.id)">GPS数据</el-button>
            </el-popover>
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
/** 田块信息 */
import crudField from '@/api/jf/field'
import CRUD, { crud, form, header, presenter } from '@crud/V2/crud'
import crudOperation from '@crud/V2/CRUD.operation'
import pagination from '@crud/V2/Pagination'
import rrOperation from '@crud/V2/RR.operation'
import udOperation from '@crud/V2/UD.operation'
import { mapGetters } from 'vuex'

const defaultForm = {
  id: null,
  farm_id: null,
  field_code: null,
  field_name: null,
  field_area: null,
  position: null,
  createBy: null,
  updateBy: null,
  create_time: null,
  update_time: null,
  remark: null
}
export default {
  name: 'Field',
  components: { pagination, crudOperation, rrOperation, udOperation },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dictsV2: ['farms'],
  cruds() {
    return CRUD({
      title: '田块信息',
      url: 'api/v2/base/farm/field',
      idField: 'id',
      sort: 'id,desc',
      crudMethod: { ...crudField }
    })
  },
  data() {
    return {
      popoverVisible: {},
      gpsForm: {
        id: null,
        position: [],
        acreage: null
      },
      fileList: [{ id: '001', name: 'food.jpeg', url: '/api/v2/public/getImage?id=11' }],
      permission: {
        add: ['admin', 'field:add'],
        edit: ['admin', 'field:edit'],
        del: ['admin', 'field:del']
      },
      rules: {
        id: [{ required: true, message: '不能为空', trigger: 'blur' }]
      },
      queryTypeOptions: [
        { key: 'field_code', display_name: '田块编号' },
        { key: 'field_name', display_name: '田块名称' },
        { key: 'farm_id', display_name: '所属农场' }
      ]
    }
  },
  computed: {
    ...mapGetters(['baseApi'])
  },
  methods: {
    // 新增与编辑前做的操作
    [CRUD.HOOK.afterToCU](crud, form) {
      // console.log(form.images)
      this.fileList = []
      if (form.images != null) {
        for (let index = 0; index < form.images.length; index++) {
          const imageId = form.images[index]
          this.fileList.push({
            id: imageId,
            name: imageId,
            url: this.baseApi + '/api/v2/public/getImage?id=' + imageId
          })
        }
      }
    },
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    [CRUD.HOOK.beforeValidateCU](crud) {
      // 检查并整理图片数据
      crud.form.oldImages = []
      crud.form.newImages = []
      var files = this.$refs.upload.uploadFiles
      for (var i = 0; i < files.length; i++) {
        var file = files[i]
        if (files[i].hasOwnProperty('raw')) {
          var imglist = ['image/png', 'image/jpg', 'image/jpeg', 'image/bmp', 'image/gif']
          var isImage = imglist.some(function(item) {
            return item === file.raw.type
          })
          const isLt2M = file.raw.size / 1024 / 1024 < 0.5
          if (!isImage) {
            crud.notify('上传图片只能是图片格式!', CRUD.NOTIFICATION_TYPE.ERROR)
            return false
          }
          if (!isLt2M) {
            crud.notify('上传图片大小不能超过 512KB!', CRUD.NOTIFICATION_TYPE.ERROR)
            return false
          }
          crud.form.newImages.push(file.raw)
        } else {
          crud.form.oldImages.push(file.id)
        }
      }
      // magic-api不支持数组参数，转为字符
      // crud.form.oldImages = crud.form.oldImages.toString()
      return true
    },
    [CRUD.HOOK.afterValidateCU](crud) {
      // console.log(crud.form)
      // return
    },
    [CRUD.HOOK.afterSubmit](crud) {
      console.log('afterSubmit')
      this.fileList = []
    },
    [CRUD.HOOK.beforeAddCancel](crud) {
      this.fileList = []
    },
    [CRUD.HOOK.beforeEditCancel](crud) {
      this.fileList = []
    },
    // 显示GPS数据面板
    showPopver(row) {
      var position = row.position
      if (position === null || position.length === 0) {
        position = []
        position.push({
          latitude: '',
          longitude: ''
        })
      }
      this.gpsForm = { id: row.id, position: JSON.parse(JSON.stringify(position)) }
    },
    // 增加坐标点
    addPosition(position) {
      this.gpsForm.position.push({
        latitude: 0,
        longitude: 0
      })
    },
    // 删除坐标点
    removePosition(position, index) {
      this.gpsForm.position.splice(index, 1)
    },
    // 保存点位
    savePosition(row) {
      var position = []
      this.gpsForm.position.forEach(function(gps) {
        if (parseFloat(gps.latitude) !== 0 && parseFloat(gps.longitude) !== 0) {
          position.push({ latitude: parseFloat(gps.latitude), longitude: parseFloat(gps.longitude) })
        }
      })
      this.gpsForm.position = position
      crudField.savePosition(this.gpsForm).then(response => {
        if (response.code === 1) {
          row.position = this.gpsForm.position
          this.$refs[row.id].doClose() // 关闭
        }
      })
    },
    // 使用手动打开，解决点击空白处Popover会自动关闭
    openPopover(id) {
      for (var key in this.popoverVisible) {
        this.popoverVisible[key] = false
      }
      this.popoverVisible[id] = !this.popoverVisible[id]
      console.log(this.popoverVisible)
    }
  }
}
</script>

<style scoped></style>
